package com.jade.journal.valve;

import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;

import com.jade.journal.AppenderFactory;
import com.jade.journal.JournalAppender;
import com.jade.journal.JournalEvent;
import com.jade.journal.JournalValve;
import com.jade.journal.desc.JournalDesc;

/**
 * 使用Appender记录日志。
 *
 * @author Daisy
 * @version 1.0 14-9-21 下午10:32
 */
public class AppenderValve extends JournalValve
{
    private final Map<String, JournalAppender> appenders = new HashMap<String, JournalAppender>(16);
    private AppenderFactory appenderFactory;

    @Inject
    public void setAppenderFactory(@Named ("system_journalAppenderFactory") AppenderFactory appenderFactory)
    {
        this.appenderFactory = appenderFactory;
    }

    /**
     * 处理日志事件
     *
     * @param events 日志事件
     */
    public void doHandle(JournalEvent... events)
    {
        for (JournalEvent event : events) {
            JournalDesc desc = event.getDesc();
            if (desc != null) {
                JournalAppender appender = appenders.get(desc.getName());
                if (appender == null) {
                    synchronized (appenders) {
                        appender = appenders.get(desc.getName());
                        if (appender == null) {
                            //create appender
                            appender = createAppender(desc);
                            appender.init(event);
                            appenders.put(appender.getName(), appender);
                        }
                    }
                }
                appender.append(event);
            }
        }
    }

    private JournalAppender createAppender(JournalDesc desc)
    {
        return appenderFactory.createAppender(desc);
    }
}
